# Written by roee88
# see LICENSE.txt for license information
from time import time

class PeerCache(object):
    def __init__(self):
        """
        Peer Cache
        Using a dictionary for storing peers {ip: port}
        Storing limited number of peers as set in confing
        """
        try:
            self.max = utility.config.Read("peercache", "int")
        except: # Not LH-ABC GUI
            self.max = 0
        self.peers = {}
            
    def __len__(self):
        """
        return the length of the peer cache
        """
        return len(self.peers)
    
    def remove(self, ip):
        """
        remove peer from cache
        """
        try:
            del self.peers[ip]
        except KeyError:
            pass
        
    def append(self, peer):
        """
        adding a peer to the peer cache
        each peer is a dictionary like {ip: str, port: int}
        or a touple like ((ip, port), 0)
        """
        if self.max == 0:
            return
        
        if type(peer) is dict:
            ip = peer["ip"]
            port = peer["port"]
        else:
            ip, port = peer[0]

        # make sure not more than max
        if  len(self) >= self.max:
            self.remove(self.peers.keys()[0])
        self.peers[ip] = port
        
    def add(self, peers):
        """
        add a list of peers to the cache
        """
        if self.max == 0:
            return
        for peer in peers:
            self.append(peer)
            
    def get(self, max = None, save = False):
        if save:
            peers = [((ip, self.peers[ip]), 0) for ip in self.peers.keys()]
        else:
            peers = [((ip, self.peers[ip]), 0, None) for ip in self.peers.keys()]
        if max:
            peers.sort(reverse=True)
            return peers[:max]
        return peers
            
    def getport(self, ip):
        """
        get the port of the peer from the cache
        """
        return self.peers[ip]

    def setport(self, ip, port):
        if self.exists(ip):
            self.peers[ip] = port
        
    def exists(self, ip):
        return self.peers.has_key(ip)

